using AliCloudDNSResolution.Application.Contract.Modules;
using Microsoft.Extensions.Options;

namespace AliCloudDNSResolution.Application.Contract;

public class AliCloudDnsResolutionWorker(IConfiguration configuration, AddrIpService addrIpService,
        DnsResolutionService dnsResolutionService, IOptions<AliCloudAccessOptions> access,
        ILogger<AliCloudDnsResolutionWorker> logger)
    : BackgroundService
{
    private readonly AliCloudAccessOptions _access = access.Value;

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            logger.LogDebug("解析DNS动态更新ip服务{0}",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            var updateDomainRecordList =
                configuration.GetSection(UpdateDomainRecordInput.Name).Get<UpdateDomainRecordInput[]>();

            var ip = await addrIpService.GetAddressIpAsync();

            foreach (var recordInput in updateDomainRecordList)
            {
                recordInput.Value = ip;
            }

            var result = await dnsResolutionService.GetDescribeDomainRecordsAsync();

            var addUpdateDomainRecord = new List<UpdateDomainRecordInput>();
            
            foreach (var item in updateDomainRecordList)
            {
                var data = result.FirstOrDefault(x => x.Type == item.Type && x.RR == item.RR);
                if (data == null)
                {
                    var recordId = await dnsResolutionService.CreateDomainRecordAsync(item);
                    item.RecordId = recordId;
                    addUpdateDomainRecord.Add(item);
                }
                else
                {
                    if (data.Value == ip)
                    {
                        continue;
                    }
                    item.RecordId = data.RecordId;
                    addUpdateDomainRecord.Add(item);
                }
            }

            await dnsResolutionService.UpdateDomainRecordListAsync(addUpdateDomainRecord);

            logger.LogDebug("时间：{0} 动态更新IP{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), addUpdateDomainRecord.Count);
            await Task.Delay(_access.TaskTime * (60 * 1000), stoppingToken);
        }
    }
}